<?php

namespace C\S\Housing;

use C\L\Service;
use C\S\Sys\Signin as SysSignin;

class Signin extends Service
{

    protected function setModel()
    {
        $this->model = new \C\M\Signin();
    }

    public function sign($uid)
    {
        try {
            $dateStr = date("Y-m-d");
            $time = strtotime($dateStr);
            $timestamp = [$time, $time + 86400];
            $data = $this->getCount(['u_id' => $uid, 'addtime' => $timestamp], [
                'u_id' => '=',
                'addtime' => 'between'
            ]);
            if ($data > 0) {
                throw new \Exception('今天您已签到');
            }
            // $housing = $this->di['s_config']->get('housing');
            // $sign_money = $housing['sign_money'];

            $this->di['db']->begin();

            $where['u_id'] = $uid;
            $where['is_delete'] = 0;
            $last_info = $this->model->get($where, [], [], 'addtime desc');

            $addData['u_id'] = $uid;
            //判断是否连续
            if (!$last_info) {
                $addData['days'] = 1;//第一天签到
            } else {
                $last_timestamp = strtotime(date('Y-m-d', $last_info['addtime']));

                if ($time - $last_timestamp > 24*3600) {
                    $addData['days'] = 1;
                } else {
                    $addData['days'] = $last_info['days']+1;
                }
            }

            $sign = $this->save($addData);

            $reward_info =  $this->di['s_syssignin']->getDetail(['type'=>1,'day'=>date('Ymd')]);
            if ($reward_info) {
                if ($reward_info['reward_type'] == 1) {
                    //发红包
                    if (!$this->di['s_funds']->add($uid, $reward_info['reward_num'], 'money', 'checkin', "签到奖励", $sign)) {
                        throw new \Exception('流水添加失败');
                    }
                } elseif ($reward_info['reward_type'] == 2) {
                    //发代金券
                    $coupon = [];
                    $coupon['uid'] = $uid;
                    $coupon['coupon_id'] = $reward_info['reward_num'];
                    $coupon['effective_time'] = $reward_info['coupon']['effective_time'];
                    $coupon_res = $this->di['s_coupon_receive']->couponReceiveCreate($coupon);
                    if (!$coupon_res) {
                        throw new \Exception('代金券发放失败');
                    }
                }

                $user_reward = [];
                $user_reward['uid'] = $uid;
                $user_reward['sys_signin_id'] = $reward_info['id'];
                $user_reward['reward'] = json_encode($reward_info, JSON_UNESCAPED_SLASHES);

                if (!(new \C\M\SigninUserReward())->save($user_reward)) {
                    throw new \Exception('奖励流水记录失败');
                }
            }

            $this->di['db']->commit();
            return ['days'=>$addData['days'], 'reward'=>$reward_info];
        } catch (\Exception $exception) {
            if ($this->di['db']->isUnderTransaction()) {
                $this->di['db']->rollback();
            }
            $this->di['message']->setSerMsg($exception->getMessage());
            return false;
        }
    }

    public function sendReward($uid, $sys_signin_id)
    {
        try {
            $reward_info =  $this->di['s_syssignin']->getDetail(['id'=>$sys_signin_id]);

            if (!$reward_info) {
                throw new \Exception('数据不存在');
            }

            $user_signin_reward = $this->di['s_signin_user_reward']->getDetail(['uid'=>$uid,'sys_signin_id'=>$sys_signin_id]);

            if ($user_signin_reward) {
                throw new \Exception('奖励不可重复领取');
            }

            //判断是否符合领取条件

            if ($reward_info['reward_type'] == 1) {
                //发红包
                if (!$this->di['s_funds']->add($uid, $reward_info['reward_num'], 'money', 'checkin', "签到奖励", $sign)) {
                    throw new \Exception('流水添加失败');
                }
            } elseif ($reward_info['reward_type'] == 2) {
                //发代金券
                $coupon = [];
                $coupon['uid'] = $uid;
                $coupon['coupon_id'] = $reward_info['reward_num'];
                $coupon['effective_time'] = $reward_info['coupon']['effective_time'];
                $coupon_res = $this->di['s_coupon_receive']->couponReceiveCreate($coupon);
                if (!$coupon_res) {
                    throw new \Exception('代金券发放失败');
                }
            }

            $user_reward = [];
            $user_reward['uid'] = $uid;
            $user_reward['sys_signin_id'] = $reward_info['id'];
            $user_reward['reward'] = json_encode($reward_info, JSON_UNESCAPED_SLASHES);

            if (!(new \C\M\SigninUserReward())->save($user_reward)) {
                throw new \Exception('奖励流水记录失败');
            }

            return $reward_info;
        } catch (\Exception $exception) {
            if ($this->di['db']->isUnderTransaction()) {
                $this->di['db']->rollback();
            }
            $this->di['message']->setSerMsg($exception->getMessage());
            return false;
        }
    }

    public function thisMonthSignin($conditions = '')
    {
        $days = $this->model->find(
            [
                        'conditions' => 'is_delete=0 AND '.$conditions,
                    ]
        )->count();
        return $days;
    }

    public function getDateList($sdate, $edate)
    {
        $list = [];
        $stime = strtotime($sdate);
        $etime = strtotime($edate);
        for ($i=$stime; $i<=$etime; $i += 86400) {
            $list[] = date('Ymd', $i);
        }
        return $list;
    }
}
